package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.StringUtil;
import org.brisling.medical.domain.BaseOutpatient;
import org.brisling.medical.service.RecipelService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


/**
 * 
 * <p>Title: QueryBaseOutpatientService</p>
 * <p>Description: service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午9:59:40
 */
@RestController
@RequestMapping("/baseOutpatient/query")
public class QueryBaseOutpatientService extends AbstractBaseQueryService<BaseOutpatient>{
	
	
	
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;

	@Autowired
	private RecipelService qryService;
	
	public QueryBaseOutpatientService(){
		this.moduleName = ConstSysParam.MODULE_BASE_OUTPATIENT;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = BaseOutpatient.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_anti_dose/"+_page);
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<BaseOutpatient> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){	
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<BaseOutpatient> getDeptListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}			
			//查找科室数据		
		}
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", "1");		
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}

	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BaseOutpatient> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BaseOutpatient> getList(String st, String en){
		
		String sql = String.format("select * from %1$s where start_time >= to_date('%2$s 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and start_time <= to_date('%3$s 23:59:59', 'yyyy-mm-dd hh24:mi:ss')",
				this.tableName, st, en); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<BaseOutpatient> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<BaseOutpatient> inlists =countMedicalInpatient (year_month,start,end,null);
			
			
			if(inlists!=null ){				
//				BaseOutpatientService.save(inlists);
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<BaseOutpatient>();
	}
	
	/**
	 * 执行自动统计
	 */
	public List<BaseOutpatient> autoMonitor(Integer yearF, Integer monthF, Integer dayF, Integer yearT, Integer monthT,
			Integer dayT){
		
		String[] yesterday = getParamDate(yearF, monthF, dayF, yearT, monthT, dayT);
		
		List<BaseOutpatient> inlists = countMedicalInpatient(yesterday[0],yesterday[1],yesterday[2],null);
		
		
		List<BaseOutpatient> oldLists = this.getList(yesterday[1], yesterday[2]);
		LinkedHashMap<String,BaseOutpatient> lmap = new LinkedHashMap<String,BaseOutpatient>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				BaseOutpatient b = oldLists.get(i);
				String _key = null;
				//以下部分需要字段支持
				_key = b.getPrescribe_code();
				lmap.put(_key, b);
			}
		}
		
		
		if(inlists!=null ){
			
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					BaseOutpatient b = inlists.get(i);
					String _key = null;
					//以下部分需要字段支持
					_key = b.getPrescribe_code();
					if(lmap.containsKey(_key)){
						inlists.get(i).setId(lmap.get(_key).getId());
					}
					else{
						System.out.println();
					}
				}
			}
			
//			BaseOutpatientService.save(inlists);			
		}	
		return inlists;
	}
	
	private String[] getParamDate(Integer yearF, Integer monthF, Integer dayF, Integer yearT, Integer monthT,
			Integer dayT) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, -1);
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DATE);
		if(yearT == null || monthT == null || dayT == null){
			yearT = year;
			monthT = month;
			dayT = day;
		}
		if(yearF == null || monthF == null || dayF == null){
			yearF = year;
			monthF = month;
			dayF = day;
		}
		String[] ret = {
				year + "-" + month,
				yearF + "-" + monthF + "-" + dayF,
				yearT + "-" + monthT + "-" + dayT
		};
		return ret;
	}
//	public void autoUpdateStandard(Integer year,Integer month){
//		String[] yestodayMonth = null;
//		if(year ==null || month ==null)
//			yestodayMonth = DateUtil.getYestodayMonthDay();
//		else{
//			yestodayMonth = DateUtil.getMonthDay(year, month);
//		}
//		BaseOutpatientService.updateStandard(yestodayMonth[2]);
//	}
	/*
	 * select 
        o.PRESCRIBE_CODE,O.DOCT_CODE,O.DOCT_DEPART_CODE, O.PATIENT_NO,O.PATIENT_NAME,o.feeat start_time,
        max(f.feeat) end_time,
        sum(case when D.IS_ANTIBIOTIC_LEVEL=1  then 1 else 0 end)is_anti,
        sum(case when D.IS_ANTIBIOTIC_LEVEL=1 then 
            (case when f.tatol_price is null then 0 else f.tatol_price end)
            else 0 end) anti_drug_amount,
        sum(case when is_basic_drug=1  then 1 else 0 end)is_base,
        sum(case when is_basic_drug=1 then 
            (case when f.tatol_price is null then 0 else f.tatol_price end)
            else 0 end) base_drug_amount,
        count(f.prescribe_code) drug_num,
        sum(f.TATOL_PRICE ) all_price,
        max(f.USE_DAY_NUM ) day_num
    from v_medical_outpatient o 
    left join v_medical_outpatient_fee f on O.PRESCRIBE_CODE = F.PRESCRIBE_CODE
    left join (select * from TA_GLJK_DRUG where rowid in (select max(rowid) from TA_GLJK_DRUG group by drug_code))d on f.DRUG_CODE = d.DRUG_CODE
    where o.feeat >= to_date('2016-8-1 00:00:00','yyyy-MM-dd hh24:mi:ss') 
        and o.feeat <= to_date('2016-8-31 23:59:59','yyyy-MM-dd hh24:mi:ss') 
        and o.prescribe_code like 'cf%'
        and f.is_drug = 1
    group by o.PRESCRIBE_CODE,O.DOCT_CODE,O.DOCT_DEPART_CODE, O.PATIENT_NO,O.PATIENT_NAME,o.feeat
	 * 
	 * 
	 * 
	 * 
	 */
	/**
	 * 统计住院患者抗菌药物使用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<BaseOutpatient> countMedicalInpatient(String year_month,String startDate ,String endDate,String countType){
		
		
		
		//出院病人统计语句
		String[] sqlids= {"medical_base_outpatient"};		
		
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		String sql = qryDictionaryService.getSqlByBizcode(sqlids[0]);
		
		if(sql!=null){
			Map<String,String> paramMap = new HashMap<String,String>();
			//溶媒排除参数
			String excludeCode = SysConfig.getConfig(ConstSysParam.MENSTRUUMCODE);
			
			if(null !=excludeCode){
				paramMap.put(ConstSysParam.MENSTRUUMCODE, excludeCode);
				
			}
			
			//超限处方指标参数
			String back = SysConfig.getConfig("overlayPrescribeStander");
			String[] arguLB = null;
			if(back != null){
				arguLB = back.split(",");
			}			
			
			if(arguLB != null && arguLB.length > 0){
				if(arguLB[0] != null && (!arguLB[0].equals("")) && Long.valueOf(arguLB[0]) >= 0){
					paramMap.put("drug_type_standard", arguLB[0]);
				}
				if(arguLB.length > 1){
					if(arguLB[1] != null && (!arguLB[1].equals("")) && Long.valueOf(arguLB[1]) >= 0){
						paramMap.put("drug_price_standard", arguLB[1]);
					}
					if(arguLB.length > 2){
						if(arguLB[2] != null && (!arguLB[2].equals("")) && Long.valueOf(arguLB[2]) >= 0){
							paramMap.put("drug_date_standard", arguLB[2]);
						}
					}
				}
			}
			
			sql = StringUtil.formatSql(paramMap, sql);
			sqls.add(sql);
		}
		//所有数据
		List<BaseOutpatient> lists = super.countBase(startDate,endDate,sqls);		
		
		return lists;
		
	}
	
	
	
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public BaseOutpatient getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public BaseOutpatient getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	@RequestMapping("/getListPatientDomain.action")
	public ListDomain<BaseOutpatient> getListPatientDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		Map<String, Object> condition = (Map<String, Object>)map.get("condition");
		if(condition == null || condition.isEmpty()){
			return null;
		}
		String mym = (String)condition.get("monitor_year_month");
		String[] yearMonth = mym.split("-");
		Integer year = null, month = null;
		if(yearMonth.length > 0 && yearMonth[0] != null && Integer.valueOf(yearMonth[0]) > 0){
			year = Integer.valueOf(yearMonth[0]);
		}
		if(yearMonth.length > 1 && yearMonth[1] != null && Integer.valueOf(yearMonth[1]) > 0 && Integer.valueOf(yearMonth[1]) < 12){
			month = Integer.valueOf(yearMonth[1]);
		}
		String[] monthDay = null;
		if(year == null || month == null){
			monthDay = DateUtil.getYestodayMonthDay();
		}
		else{
			monthDay = DateUtil.getMonthDay(year, month);
		}
		String doct_code = (String)condition.get("doct_code");
		if(doct_code == null || doct_code.length() < 1){
			return null;
		}
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){			
			addJobDeptConditionToMap(userid,map,"dept_code");			
			//查找科室数据		
		}
		//查询表
		String sql = null;
		sql = SysConfig.getBizidSql("overlay-prescribe-patient");
		if(sql == null || sql.equals("") || sql.length() < 1){
			sql = "select BO.* from medical_base_outpatient bo where ((BO.ALL_WESTERN_PRICE > 500 and BO.GOLD_MEDICAL = 0) or BO.DAY_NUM > 7) and start_time >= to_date('%1$s 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and start_time <= to_date('%2$s 23:59:59', 'yyyy-mm-dd hh24:mi:ss') and doct_code = '%3$s' ";
		}
		sql = String.format(sql, monthDay[0], monthDay[1], doct_code);
		
		Integer[] pageParam = LongUtil.getPageParam(map);
		
		ListDomain<BaseOutpatient> domains = super.getPagedListDomain(pageParam[0], pageParam[1], sql);
		return domains;
		
		
	}
	
}
